package com.tbit.uqbike.config.datasource;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.tbit.uqbike.config.datasource.properties.DruidProperties;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author chenzhuang
 */
@Configuration
@MapperScan(basePackages = "com.tbit.uqbike.client.dao.huge", sqlSessionFactoryRef = "hugeSqlSessionFactory")
public class HugeSource {
    /**
     * 返回huge数据库的数据源
     *
     * @return
     */
    @Bean(name = "hugeDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.huge")
    public DataSource dataSource(DruidProperties druidProperties) {
        return druidProperties.dataSource(DruidDataSourceBuilder.create().build());
    }

    @Bean(name = "hugeMybatisProperties")
    @ConfigurationProperties(prefix = "mybatis.huge")
    public MybatisProperties mybatisProperties() {
        return new MybatisProperties();
    }

    /**
     * 返回huge数据库的会话工厂
     *
     * @param ds
     * @return
     * @throws Exception
     */
    @Bean(name = "hugeSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("hugeDataSource") DataSource ds, @Qualifier("hugeMybatisProperties") MybatisProperties mybatisProperties) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(ds);
        bean.setMapperLocations(mybatisProperties.resolveMapperLocations());
        bean.setTypeAliasesPackage(mybatisProperties.getTypeAliasesPackage());
        org.apache.ibatis.session.Configuration configuration = mybatisProperties.getConfiguration();
        //configuration.setLogImpl(StdOutImpl.class);
        bean.setConfiguration(configuration);
        return bean.getObject();
    }

    /**
     * 返回huge数据库的会话模板
     *
     * @param sessionFactory
     * @return
     */
    @Bean(name = "hugeSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("hugeSqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }

    /**
     * 返回huge数据库的事务
     *
     * @param ds
     * @return
     */
    @Bean(name = "hugeTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("hugeDataSource") DataSource ds) {
        return new DataSourceTransactionManager(ds);
    }
}
